<template>
  <div class="spuForm">
    <el-form label-width='100px'>
      <el-form-item label="SPU名称">
        <el-input placeholder="请输入SPU名称" v-model="spuForm.spuName"></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select placeholder="请选择品牌" v-model="spuForm.tmId">
          <el-option v-for="item in spuForm.tradeMarkList" :label="item.tmName" :value="item.id"
            :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" placeholder="请输入描述" v-model="spuForm.description"> </el-input>
      </el-form-item>
      <el-form-item label="SPU照片">
        <el-upload v-model:file-list="spuImageList" action="/api/admin/product/fileUpload" list-type="picture-card"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU销售属性">
        <el-select v-model="saleAttrIdAndValueName"
          :placeholder="unSelectSaleAttr.length ? `还有${unSelectSaleAttr.length}个可选择的选项` : '无'">
          <el-option v-for="item in unSelectSaleAttr" :label="item.name" :value="`${item.id}:${item.name}`"
            :key="item.id"></el-option>
        </el-select>
        <el-button type="primary" icon="Plus" @click="addSpuSaleAttr" :disabled="saleAttrIdAndValueName ? false : true"
          style="margin: 0px 0px 0px 20px;">添加销售属性</el-button>
      </el-form-item>
    </el-form>
    <el-table border :data="spuSaleAttrList" style="margin:0px 0px 20px 0px;">
      <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
      <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
      <el-table-column label="属性值">
        <template #="{ row, $index }">
          <el-tag v-for="(tag, index) in row.spuSaleAttrValueList" :key="tag.id"
            @close="row.spuSaleAttrValueList.splice(index, 1)" closable style="margin:0px 5px">
            {{ tag.saleAttrValueName }}
          </el-tag>
          <el-button v-if="!row.flag" type="primary" size="small" icon="Plus"
            @click="addSpuSaleTag(row, $index)"></el-button>
          <el-input ref="inputArr" v-if="row.flag" v-model="row.saleAttrValue" placeholder="请你输入属性值"
            @blur="toLook(row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #="{ row, $index }">
          <el-button icon="Delete" size="small" type="danger" @click="spuSaleAttrList.splice($index, 1)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="saveSpu">保存</el-button>
    <el-button @click="cancel">取消</el-button>
  </div>
</template>
<script setup lang='ts'>
import { onBeforeMount, onMounted, ref, computed, nextTick } from 'vue'
import { tradeMarkListAPI, spuImageListAPI, spuSaleAttrListAPI, baseSaleAttrListAPI, saveAndUpdateSpuInfo } from '@/api/product/spu/index.ts'
import { ElMessage } from 'element-plus';
import useCategoryStore from '@/store/modules/category';

let categoryStore = useCategoryStore()
const $emits = defineEmits(['changeScene'])
let spuForm = ref({
  spuName: '', //spu名称
  description: '', //描述
  category3Id: '', //三级分类id
  tmId: '', //品牌id
  tradeMarkList: [], //品牌列表
  spuImageList: [],//照片列表
  spuSaleAttrList: [] //销售属性列表
})
//spu图片列表
let spuImageList = ref([])
// spu基础销售属性列表
let baseSaleAttrList = ref([])
// spu销售属性列表
let spuSaleAttrList = ref([])
// 图片预览弹窗
let dialogVisible = ref<boolean>(false)
// 预览图片地址
let dialogImageUrl = ref<string>('')
// spu销售属性下拉选择框绑定的值
let saleAttrIdAndValueName = ref<string>('')
// 输入框dom元素
let inputArr = ref('')
// 取消按钮
const cancel = () => {
  $emits('changeScene', 0)
}
// 修改某一项spu调用四个接口，获取spu相关信息
const initSpuData = async (spu) => {
  spuForm.value = spu
  // 调用四个接口获取相关数据
  let tradeMarkList = await tradeMarkListAPI()
  let spuImageListapi = await spuImageListAPI(spu.id)
  let spuSaleAttrListapi = await spuSaleAttrListAPI(spu.id)
  let baseSaleAttrListapi = await baseSaleAttrListAPI()
  spuForm.value.tradeMarkList = tradeMarkList.data
  spuImageList.value = spuImageListapi.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl
    }
  })
  spuSaleAttrList.value = spuSaleAttrListapi.data
  baseSaleAttrList.value = baseSaleAttrListapi.data

}
// 添加一项新的spu
const addSpuData = async () => {
  // 先清空原表单数据
  spuForm.value = {
    spuName: '', //spu名称
    description: '', //描述
    category3Id: '', //三级分类id
    tmId: '', //品牌id
    tradeMarkList: [], //品牌列表
    spuImageList: [],//照片列表
    spuSaleAttrList: [] //销售属性列表
  }
  console.log(spuForm.value, '333');
  // 清空spu销售属性
  spuSaleAttrList.value = []
  // 清空图片列表
  spuImageList.value = []
  saleAttrIdAndValueName.value = ''
  // 获取品牌列表
  let tradeMarkList = await tradeMarkListAPI()
  // 获取基础销售属性列表
  let baseSaleAttrListapi = await baseSaleAttrListAPI()
  spuForm.value.tradeMarkList = tradeMarkList.data
  baseSaleAttrList.value = baseSaleAttrListapi.data
}
//计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  //全部销售属性:颜色、版本、尺码
  //已有的销售属性:颜色、版本
  let unSelectArr = baseSaleAttrList.value.filter(baseSale => {
    return spuSaleAttrList.value.every(spuSale => {
      return baseSale.name != spuSale.saleAttrName;
    });
  })
  return unSelectArr;
})
// 图片在线预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
// 删除图片
const handleRemove = (uploadFile) => {
  console.log(uploadFile);
}
// 删除某个spu销售属性
const deleteSpuSale = (spu) => {

}
// 添加某个spu销售属性标签tag
const addSpuSaleTag = (row, $index) => {
  row.flag = true
  row.saleAttrValue = ''
  // 获取焦点
  nextTick(() => {
    inputArr.value.focus()
  })
}
// 输入框的失焦事件
const toLook = (row) => {
  //整理收集的属性的ID与属性值的名字
  const { baseSaleAttrId, saleAttrValue } = row;
  // 构建一个新对象，这个对象包含baseSaleAttrId和saleAttrValueName两个字段
  let newSpuAttr = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue
  }
  // 如果当前添加的新的tag值为空，那么不允许添加
  if (saleAttrValue.trim() == '') {
    ElMessage.warning('属性值不能为空')
    row.flag = false
    return
  }
  // 如果新对象的saleAttrValueName在现有的spuSaleAttrValueList存在，那么证明添加的是重复的tag值
  let repeat = row.spuSaleAttrValueList.find(item => {
    return item.saleAttrValueName == saleAttrValue
  })
  if (repeat) {
    ElMessage.warning('不允许添加重复的属性值')
    row.flag = false
    return
  }
  // 将这个新生成的对象push到spuSaleAttrValueList中
  row.spuSaleAttrValueList.push(newSpuAttr)
  // 将此时的flag置为false，展示按钮状态
  row.flag = false

}
// 保存修改的spu信息
const saveSpu = async () => {
  // 整理数据，用于接口传参
  spuForm.value.spuImageList = spuImageList.value.map(item => {
    return {
      imgName: item.name,//图片的名字
      imgUrl: (item.response && item.response.data) || item.url
    }
  })
  //2:整理销售属性的数据
  spuForm.value.spuSaleAttrList = spuSaleAttrList.value;
  spuForm.value.category3Id = categoryStore.category3Id
  let result = await saveAndUpdateSpuInfo(spuForm.value)
  const { code, data } = result
  if (code == 200) {
    console.log(data);
    ElMessage.success('保存成功')
    // 重新获取列表数据
    $emits('changeScene', 0)
  } else {
    ElMessage.error('保存失败')
  }
}
// 添加销售属性
const addSpuSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  // 定义一个新对象，保存当前的销售属性
  let newSaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  // 追加到表格数组中
  spuSaleAttrList.value.push(newSaleAttr)
  // 将选择框中的数据清空
  saleAttrIdAndValueName.value = ''

}
onBeforeMount(() => {

})
onMounted(() => {

})
defineExpose({ initSpuData, addSpuData })
</script>
<style lang="scss" scoped>
.el-select {
  width: 200px
}
</style>